﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraWaitForm;
using DevExpress.XtraGrid.Columns;
using BartonExtension;
using Model;
using ResponseObject;

namespace Backend
{
    public partial class FrmStore : DevExpress.XtraEditors.XtraForm
    {
        public NewStore store { get; set; }
        public List<StoreCatalog> tempCatalogs { get; set; }
        private bool cancelTag { get; set; }
        public FrmStore()
        {
            InitializeComponent();
            Init();
        }

        void Init()
        {
            //Load Type
            cmbType.Properties.Items.AddRange(Enum.GetNames(typeof(StoreType)));
            lkMall.Properties.NullText = "Loading...";
            lkMall.Enabled = false;
            WebServiceHelper.LoadMalls((m, err) =>
                {
                    if(err != null)
                    {
                        XtraMessageBox.Show(err.Message);
                        return;
                    }
                    lkMall.Invoke(new Action(() =>
                        {
                            lkMall.Properties.ValueMember = "ID";
                            lkMall.Properties.DisplayMember = "name";
                            lkMall.Properties.DataSource = m;
                            lkMall.Properties.NullText = "Select mall";
                            lkMall.Enabled = true;
                        }));
                });
            store = new NewStore() { catalogs = new List<StoreCatalog>() };
            tempCatalogs = new List<StoreCatalog>();
            cancelTag = false;
        }

        private void setup_one_PageCommit(object sender, EventArgs e)
        {
            Utils.IndicatorShowHide(this, true);
            if (chklstCatalogs.Items.Count > 0)
                return;
            Utils.IndicatorShowHide(this, true);
            WebServiceHelper.LoadCatalogs((x, err) =>
            {
                if (err != null)
                {
                    Utils.IndicatorShowHide(this, false);
                    XtraMessageBox.Show(err.Message);
                    return;
                }
                var maxLayer = x.Max(p => p.layer);
                List<Catalog> finalLayer = x.Where((n, index) =>
                {
                    return n.layer == maxLayer;
                }).ToList<Catalog>();
                chklstCatalogs.Invoke(new Action(() =>
                {
                    finalLayer.ForEach(f =>
                    {
                        chklstCatalogs.Items.Add(f, f.title_en);
                    });
                    Utils.IndicatorShowHide(this, false);
                }));
            });
        }
        private void setup_catalogs_PageCommit(object sender, EventArgs e)
        {
            Utils.IndicatorShowHide(this, true);

            //Clean
            gvDetail.Columns.Clear();
            gcDetail.DataSource = null;
            gvDetail.RefreshData();

            //Initial Unbound brand
            //GridColumn unbound_col = gvDetail.Columns.AddField("value");
            //unbound_col.Caption = "";
            //unbound_col.VisibleIndex = gvDetail.Columns.Count;
            //unbound_col.Visible = true;
            //unbound_col.UnboundType = DevExpress.Data.UnboundColumnType.String;
            //unbound_col.OptionsColumn.AllowEdit = false;
            //unbound_col.AppearanceCell.BackColor = Color.LemonChiffon;

            List<StoreCatalog> c = new List<StoreCatalog>();
            CheckedListBoxControl.CheckedItemCollection collection = chklstCatalogs.CheckedItems as CheckedListBoxControl.CheckedItemCollection;
            for (int i = 0; i < collection.Count; i++)
            {
                Catalog catalog = collection[i] as Catalog;
                StoreCatalog s_catalog = new StoreCatalog()
                {
                    top_price = 0,
                    low_price = 0,
                    isFeatured = false,
                    catalog = catalog
                };
                c.Add(s_catalog);
            }
            GridColumn column = new GridColumn();
            column.Caption = "Catalog Data";
            column.Name = "col_data";
            column.Visible = true;
            column.VisibleIndex = gvDetail.Columns.Count;
            column.FieldName = "value";
            column.ColumnEdit = valueEdit;
            gvDetail.Columns.Add(column);
            tempCatalogs = c;
            gcDetail.DataSource = tempCatalogs;
            Utils.IndicatorShowHide(this, false);
        }

        private void valueEdit_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            int rowHandle = gvDetail.FocusedRowHandle;
            try
            {
                int dataSourceIndex = gvDetail.GetDataSourceRowIndex(rowHandle);
                using (CellEditor frm = new CellEditor(tempCatalogs[dataSourceIndex]))
                {
                    frm.ShowDialog();
                    if (frm.result == System.Windows.Forms.DialogResult.OK)
                    {
                        tempCatalogs[dataSourceIndex] = frm.sc;
                        gcDetail.DataSource = tempCatalogs;
                        gvDetail.RefreshData();
                    }
                }
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void lkMall_Properties_EditValueChanged(object sender, EventArgs e)
        {
            try
            {
                Mall selectedMall = lkMall.GetSelectedDataRow() as Mall;
                txtLat.Text = selectedMall.latitude.ToString();
                txtLon.Text = selectedMall.longitude.ToString();
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            //Validate 

            try
            {
                Utils.IndicatorShowHide(this, true);
                store.title = txtTitle.Text;
                store.type = (StoreType)Enum.Parse(typeof(StoreType), cmbType.SelectedItem.ToString());
                store.frequency = spinFreq.EditValue.toFloat().Value;
                store.duration = spinDuration.EditValue.toFloat().Value;
                store.in_mall_location = txtMallLoc.Text;
                store.mall = lkMall.GetSelectedDataRow() as Mall;
                store.lat = txtLat.Text.toFloat().Value;
                store.lon = txtLon.Text.toFloat().Value;
                store.catalogs = tempCatalogs;

                PostParams param = new PostParams();
                param.addParam("store_type", store.type);
                param.addParam("title", store.title);
                param.addParam("frequency", store.frequency);
                param.addParam("duration", store.duration);
                param.addParam("level", store.level);
                param.addParam("mall_id", store.mall.ID);
                param.addParam("in_mall_loc", store.in_mall_location);
                param.addParam("lat", store.lat);
                param.addParam("lng", store.lon);

                string catalogs = "";
                foreach(StoreCatalog catalog in store.catalogs)
                {
                    string single_str = "{0},{1},{2},{3}".FormatWith(catalog.catalog.ID,catalog.top_price, catalog.low_price, catalog.isFeatured ? 1 : 0);
                    catalogs += single_str + ";";
                }
                catalogs = catalogs.TrimEnd(';');
                param.addParam("catalogs", catalogs);

                HttpPost post = new HttpPost("{0}/apis/ZK_BackEndService.asmx/AddStore".FormatWith(AddressPool.ServerAddr), param.jsonSerialize());
                post.post((resp,err) =>
                    {
                        if(err != null)
                        {
                            this.Invoke(new Action(() =>
                                {
                                    Utils.IndicatorShowHide(this, false);
                                }));
                            XtraMessageBox.Show(err.Message);
                            return;
                        }
                        ZKResponse response = resp.FromJson<Dictionary<string, object>>()["d"].ToString().FromJson<ZKResponse>();
                        if(response.isProcessSuccess)
                        {
                            this.Invoke(new Action(() =>
                            {
                                Utils.IndicatorShowHide(this, false);
                                XtraMessageBox.Show("Store {0} added.".FormatWith(store.title));
                            }));
                        }
                        else
                        {
                            this.Invoke(new Action(() =>
                            {
                                Utils.IndicatorShowHide(this, false);
                                XtraMessageBox.Show(response.errMsg);
                            }));
                        }
                    });
            }
            catch(Exception ex)
            {
                XtraMessageBox.Show(ex.Message);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }
        private void setup_catalogs_PageValidating(object sender, DevExpress.XtraWizard.WizardPageValidatingEventArgs e)
        {
            if(chklstCatalogs.CheckedItems.Count == 0 && e.Direction == DevExpress.XtraWizard.Direction.Forward)
            {
                e.Valid = false;
                e.ErrorText = "Please select at lease one catalog";
            }
            else
            {
                e.Valid = true;
                e.ErrorText = null;
            }
        }

        private void BCWizard_FinishClick(object sender, CancelEventArgs e)
        {
            //store.matrix = matrix;
            //matrix = null;
            //tempBrands.Clear();
            //tempCatalogs.Clear();
            //chklstCatalogs.Items.Clear();
            //chklstBrands.Items.Clear();
            //gcDetail.RefreshDataSource();
            //gvMatrix.Columns.Clear();
            e.Cancel = true;
        }
        private void BCWizard_CancelClick(object sender, CancelEventArgs e)
        {
            e.Cancel = false;
            tempCatalogs.Clear();
            chklstCatalogs.Items.Clear();
            gcDetail.RefreshDataSource();
            gvDetail.Columns.Clear();
            BCWizard.SelectedPage = setup_one;
            cancelTag = true;
        }

        private void FrmStore_Load(object sender, EventArgs e)
        {
            
        }

        private void setup_detail_PageCommit(object sender, EventArgs e)
        {

        }

        private void FrmStore_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = cancelTag;
            cancelTag = false;
        }
    }
}